
import os
import sys
import time
from zipfile import ZipFile

import rpyc

from dexen.system import constants

#===============================================================================
# FUNCTIONS
#===============================================================================
def _zip_schema(dir, zip_name):
    prev_path = os.getcwd()
    os.chdir(dir)   
    if os.path.exists(zip_name):
        os.remove(zip_name)
    z = ZipFile(zip_name, "w")
      
    for root, dirs, files in os.walk("."):
        if root.find(".svn") != -1:
            continue       
        for file in files:
            if file != zip_name and not file.endswith(".pyc"):
                z.write(os.path.join(root, file))  
    z.close()
    os.chdir(prev_path)

def create_connection(svcname, cfg={"allow_custom_instantiations":True,
                                    "allow_pickle":True}):
    print "connecting to service", svcname
    conn = rpyc.connect_by_service(svcname, config=cfg)
    return conn

def create_new_schema(schema_name, schema_folder):
    """Create a new schema.
    
    A method that creates a zip file of the schema_folder and sends it to the 
    server. A new schema is created in the server with the name schema_name. 
    
    """
    file_path = os.path.join(constants.SCHEMAS_DIR, schema_folder, 
                             schema_name+".zip")      
    _zip_schema(os.path.join(constants.SCHEMAS_DIR, schema_folder), 
                schema_name+".zip")
    f = open(file_path, "rb")
    data = f.read()
    f.close()
    last_mt = os.path.getmtime(file_path) #last modified time 
                                                     #in seconds since Epoch
    #os.remove(file_path) # removes the newly created zip file
    if not pconn.root.has_schema(schema_name):
        pconn.root.set_schema(schema_name, data, last_mt)

def initialize():
    global pconn, jconn
    pconn = create_connection("BACKEND") # Gateway to -----> db_manager
    task_mgr = create_connection("TASK_MANAGER")
    while True:
        svc_name = task_mgr.root.get_free_service_name()
        if svc_name != None: break
        time.sleep(10)
    jconn = create_connection(svc_name)

def main():
    schema_name = "packing_boxes_v1"
    pop_name = "pop_asynch"
    initialize()
    create_new_schema(schema_name, schema_name)
    jconn.root.run_population(schema_name, pop_name)

if __name__ == "__main__":
    main()
    